package com.project.myshop.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtils {
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();

    private static DruidDataSource ds;

    static{
        try {
            Properties pro = new Properties();
            pro.load(DBUtils.class.getResourceAsStream("/jdbc.properties"));
            //创建数据源
            ds= (DruidDataSource) DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection con = THREAD_LOCAL.get();
        try {
            if (con == null) {
                con = ds.getConnection();
                THREAD_LOCAL.set(con);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    public static DataSource getDataSource(){
        return ds;
    }

    public static void closeAll(ResultSet rs, PreparedStatement ps , Connection con){
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (con != null) {
                con.close();
                THREAD_LOCAL.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void begin(){
        try {
            Connection con = getConnection();
            con.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void commit(){
        Connection con = getConnection();
        try {
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(null,null,con);
        }
    }
    public static void rollback(){
        Connection con = getConnection();
        try {
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(null,null,con);
        }
    }
}
